package com.atguigu.yuntai.monitor.service.impl;

import com.atguigu.yuntai.monitor.config.AlertConfig;
import com.atguigu.yuntai.monitor.entity.AlertMsg;
import com.atguigu.yuntai.monitor.entity.RuleCollection;
import com.atguigu.yuntai.monitor.entity.TriggerLog;
import com.atguigu.yuntai.monitor.service.AlertMsgService;
import com.atguigu.yuntai.monitor.service.AlertService;
import com.atguigu.yuntai.monitor.service.RuleCollectionService;
import com.atguigu.yuntai.monitor.service.TriggerLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>报警服务的实现类</p>
 **/
@Service
@Slf4j
public class AlertServiceImpl implements AlertService {

    @Autowired
    @Qualifier("alertClient")
    AlertConfig.AlertClient alertClient;

    @Autowired
    AlertMsgService alertMsgService;

    @Autowired
    TriggerLogService triggerLogService;

    @Autowired
    RuleCollectionService ruleCollectionService;


    @Override
    public void alert(Long triggerLogId,Long collectionId, String msg) {
        alert(triggerLogId,collectionId,null,msg);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void alert(Long triggerLogId, Long collectionId, Long ruleInfoComputeId, String msg) {
        AlertMsg alertMsg = new AlertMsg(triggerLogId,collectionId,ruleInfoComputeId,msg);
        // 0. 保存报警持久化
        alertMsgService.save(alertMsg);
        // 1. 将触发记录的ifAlert改为true
        triggerLogService.setIfAlertTrueById(triggerLogId);
    }

    @Override
    public void triggerAlert(Long triggerLogId) {
        List<AlertMsg> alertMsgs = alertMsgService.listAlertMsgByTriggerId(triggerLogId);
        if(alertMsgs.size()!=0){
            TriggerLog triggerLog = triggerLogService.getById(triggerLogId);
            RuleCollection ruleCollection = ruleCollectionService.getById(triggerLog.getCollectionId());
            Integer code = alertClient.alert("[数据库:" + ruleCollection.getHiveDatabase() + "].[表:" + ruleCollection.getHiveTableName() +
                    "].[触发者:" + triggerLog.getWho() + "]有(" + alertMsgs.size() + ")条报警消息");
            if(200==code){
                // 如果发送成功了，把这个触发记录下属的报警标记为已发送
                alertMsgService.updateIfSendByTriggerId(triggerLogId);
            }
        }
    }
}
